﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Net;

namespace Ecommerce.Frete
{
    public class Direct : IFrete
    {
        private static Direct instance;
        private const string linkDirect = "http://www.directlog.com.br/frete/pega_frete.asp?cdrem={0}&peso={1}&cep={2}&vltot={3}";

        private Direct()
        {

        }

        public static Direct Instance
        {
            get
            {
                if (instance == null)
                    instance = new Direct();
                
                return instance;
            }
        }

        public decimal Calcular(string cepDestino, decimal pesoPedido, decimal valorTotalPedido)
        {
            string url = string.Format(linkDirect, ConfigurationManager.AppSettings["cdremDirect"], pesoPedido.ToString().Replace(".", "").Replace(",", "."), cepDestino, valorTotalPedido.ToString().Replace(".", "").Replace(",", "."));
            decimal frete = 0;
            using (WebClient client = new WebClient())
            {
                string retorno = client.DownloadString(url);
                if (retorno.ToLower().Contains("erro"))
                    throw new Exception("Erro ao calcular o frete");
                else
                    frete = decimal.Parse(retorno.Replace(",", "").Replace(".", ","));
            }
            return frete;
        }
    }
}
